package com.ypj.indusynergyems.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ypj.indusynergyems.common.convention.exception.ClientException;
import com.ypj.indusynergyems.dao.entity.MenuEntity;
import com.ypj.indusynergyems.dao.entity.UserEntity;
import com.ypj.indusynergyems.dao.mapper.UserMapper;
import com.ypj.indusynergyems.dto.req.UserRegisterReqDTO;
import com.ypj.indusynergyems.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.ypj.indusynergyems.common.constant.RedisCacheConstant.LOCK_USER_register_KEY;
import static com.ypj.indusynergyems.common.enums.UserErrorCodeEnum.*;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements IUserService {
    private final UserMapper userMapper;
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;//看门狗机制
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public UserEntity login(String phone, String password) {
        LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery(UserEntity.class)
                .eq(UserEntity::getPhone, phone)
                .eq(UserEntity::getPassword, password)
                .eq(UserEntity::getIsLock, 0);
        UserEntity userDo = baseMapper.selectOne(queryWrapper);
        if (userDo == null){
            throw new ClientException("用户不存在");
        }
//        Boolean hasLogin = stringRedisTemplate.hasKey("login_"+phone);
//        if (hasLogin!=null && hasLogin){
//            throw new ClientException("用户已登录");
//        }
        /**
         * Hash
         * Key: login_用户名
         * Values:
         *   Key: token标识
         *   Val: JSON 字符串 （用户信息）
         */

        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put("login_"+phone,uuid, JSON.toJSONString(userDo));
        stringRedisTemplate.expire("login_"+phone,30L, TimeUnit.DAYS);
        return userDo;
    }

    @Override
    public void register(UserRegisterReqDTO registerParam) {
        if(!hasUsername(registerParam.getPhone())){
            throw new ClientException(USER_PHONE_EXIST);
        }
        //大量客户同时利用相同的电话号码登录 加锁只让一个用户进行注册其余用户返回
        RLock lock = redissonClient.getLock(LOCK_USER_register_KEY+registerParam.getPhone());
        try {
            if(lock.tryLock()){
                try {
                    int insert = baseMapper.insert(BeanUtil.toBean(registerParam, UserEntity.class));
                    if(insert<1){
                        throw new ClientException(USER_SAVE_ERROR);
                    }
                }catch (DuplicateKeyException ex){
                    throw new ClientException(USER_EXIST);
                }
                userRegisterCachePenetrationBloomFilter.add(registerParam.getPhone());
                return;
            }
            throw new ClientException(USER_PHONE_EXIST);
        }finally {
            lock.unlock();
        }
    }

    @Override
    public Boolean hasUsername(String username) {
        return  !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public List<UserEntity> findUserList(String username) {
        return userMapper.findUserList(username);
    }



}
